package com.qtong.rotatenavigation.adapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.qtong.rotatenavigation.R;
import com.qtong.rotatenavigation.R.id;
import com.qtong.rotatenavigation.R.layout;
import com.qtong.rotatenavigation.dao.SqLiteUtils;
import com.qtong.rotatenavigation.entity.IndexGrid;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

public class MainIndexAdapter extends BaseAdapter {

	private Context context;
	private AssetManager am;
	
	private List<IndexGrid> listgrid=new ArrayList<IndexGrid>();
	public MainIndexAdapter(Context context){
		this.context=context;
		initlistgrid();
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return listgrid.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return listgrid.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
	class viewholder{
		ImageView iv;
		TextView tv;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		viewholder vh;
		System.out.println(convertView==null);
		if(convertView==null){
			convertView=LayoutInflater.from(context).inflate(R.layout.main_item, null);
			vh=new viewholder();
			vh.iv=(ImageView)convertView.findViewById(R.id.indeximage);
			vh.tv=(TextView)convertView.findViewById(R.id.indextext);
			convertView.setTag(vh);
		}else{
			vh=(viewholder)convertView.getTag();
		}
		vh.iv.setImageBitmap(listgrid.get(position).getIv());
		vh.tv.setText(listgrid.get(position).getName());
		return convertView;
	}
	public void initlistgrid(){
		listgrid.clear();
		am=context.getAssets();
		SqLiteUtils su=new SqLiteUtils(context);
		Cursor cursor=su.getReadableDatabase().rawQuery("select _id,name,cid,image from indexgrid where isvisible=1", null);
		while(cursor.moveToNext()){
			IndexGrid ig=new IndexGrid();
			ig.setId(cursor.getInt(0));
			ig.setName(cursor.getString(1));
			ig.setFid(cursor.getInt(2));
			ig.setImage(cursor.getString(3));
			try {
				ig.setIv(BitmapFactory.decodeStream(am.open(ig.getImage())));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			listgrid.add(ig);
		}
		cursor.close();
		su.close();
	}

}
